//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package events_subscribe

import (
	"fmt"

	"atomgit.com/openlinksaas/proto-gen-go.git/events/events_entry"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_entry_api"
)

func getEntryTypeStr(entryType uint32) string {
	if entryType == uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_DOC) {
		return "文档"
	} else if entryType == uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_SPRIT) {
		return "工作计划"
	} else if entryType == uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_PAGES) {
		return "静态网页"
	} else if entryType == uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_BOARD) {
		return "信息面板"
	}
	return ""
}

func processEntryEvent(event *events_api.Event, cfgItemList []*CfgItem) (bool, error) {
	var err error
	var msg string

	{
		createEvent := &events_entry.CreateEvent{}
		if event.EventData.MessageIs(createEvent) {
			err = event.EventData.UnmarshalTo(createEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 创建 %s %s。", event.UserDisplayName, event.ProjectName,
				getEntryTypeStr(createEvent.EntryType), createEvent.EntryTitle)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.EntryEvCfg.Create {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	{
		removeEvent := &events_entry.RemoveEvent{}
		if event.EventData.MessageIs(removeEvent) {
			err = event.EventData.UnmarshalTo(removeEvent)
			if err != nil {
				return false, err
			}

			msg = fmt.Sprintf("%s 在项目 %s 把 %s %s 移入回收站。", event.UserDisplayName, event.ProjectName,
				getEntryTypeStr(removeEvent.EntryType), removeEvent.EntryTitle)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.EntryEvCfg.Remove {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}
	return false, nil
}
